﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using JWTAuthorize;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AuthorizeServer.Controllers
{
    public class AccountController : Controller
    {
        CustomRequirement _requirement;
        public AccountController(CustomRequirement requirement)
        {
            _requirement = requirement;
        }

        // GET api/values
        [AllowAnonymous]
        [HttpPost("/authapi/login")]
        public ActionResult Login(string username, string password)
        {
            //真实环境下，登录成功判断应该通过数据库操作
            if ((username == "admin" && password == "123") || (username == "test" && password == "456"))
            {
                string role = username == "admin" ? "admin" : "system";
                var claims = new Claim[] { new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), new Claim(ClaimTypes.Expiration, DateTime.Now.AddSeconds(_requirement.Expiration.TotalSeconds).ToString()) };
                //用户标识
                var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
                identity.AddClaims(claims);

                var token = JwtToken.CreateJwtToken(claims, _requirement);//    登录成功，返回生成的token
                return new JsonResult(token);
            }
            else
            {
                return new JsonResult(new
                {
                    Status = false,
                    Message = "用户名或者密码错误"
                });
            }
        }
    }
}
